import 'package:dio/dio.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

import 'AuthBase.dart';

// 使用单例模式的Dio服务
class DioService {
  // 私有静态实例
  static final DioService _instance = DioService._internal();

  // 工厂方法返回单例
  factory DioService() => _instance;

  // 唯一的Dio实例
  late final Dio dio;

  // 私有构造函数
  DioService._internal() {
    // 初始化Dio
    dio = Dio(BaseOptions(
      baseUrl: ApiBase.baseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    ));

    // 初始化拦截器（仅一次）
    _initInterceptors();
  }

  // 初始化拦截器
  void _initInterceptors() {
    final authBase = AuthBase();

    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        final token = authBase.getToken();
        if (token != null) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        return handler.next(options);
      },
      onResponse: (response, handler) {
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        print('API Error: ${e.message}');
        return handler.next(e);
      },
    ));

    // 开发环境添加日志拦截器
    if (const bool.fromEnvironment('dart.vm.product') == false) {
      dio.interceptors.add(PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
        responseBody: true,
      ));
    }
  }
}

abstract class ApiBase {
  // 统一的baseUrl
  static const String baseUrl = 'http://192.168.1.163:3000/gate';

  // 使用单例Dio实例
  final Dio dio = DioService().dio;

  ApiBase();
}